<template>
  <div class="register">
    <div class="close">
      <i class="iconfont iconicon-test"></i>
    </div>
    <div class="logo">
      <i class="iconfont iconnew"></i>
    </div>
    <div class="username">
      <hm-input :rules="userRule" err-msg="账号/手机号必须是5-11的数字" v-model="username" placeholder="账号/手机号码"></hm-input>
    </div>
    <div class="nickname">
      <hm-input :rules="nicknameRule" err-msg="昵称必须是2-6位的汉字" v-model="nickname" placeholder="昵称"></hm-input>
    </div>
    <div class="password">
      <hm-input :rules="passRule" err-msg="密码必须是3-12的字符" v-model="password" type="password" placeholder="密码"></hm-input>
    </div>
    <div class="register-btn">
      <hm-button @click="register">注册</hm-button>
    </div>
    <div class="go-login">
      已有账号? 立即<router-link to="/login">登录</router-link>
    </div>
  </div>
</template>

<script>
import HmInput from 'components/hm-input.vue'
import HmButton from 'components/hm-button.vue'

export default {
  data () {
    return {
      username: '',
      nickname: '',
      password: '',
      userRule: /^1\d{4,10}$/,
      passRule: /^\w{3,12}$/,
      nicknameRule: /^[\u4e00-\u9fa5]{2,6}$/
    }
  },
  components: {
    HmInput,
    HmButton
  },
  methods: {
    async register () {
      // 先校验用户的输入
      if (!this.userRule.test(this.username)) {
        this.$toast('请输入正确的账号/手机号')
        return
      }
      if (!this.nicknameRule.test(this.nickname)) {
        this.$toast('请输入正确的昵称')
        return
      }
      if (!this.passRule.test(this.password)) {
        this.$toast('请输入正确的密码')
        return
      }
      // 使用 axios 发送请求

      const res = await this.$axios.post('/register', {
        username: this.username,
        password: this.password,
        nickname: this.nickname
      })
      const { statusCode, message } = res.data
      if (statusCode === 200) {
        // 注册成功
        // 添加用户提示
        this.$toast.success(message)
        // 跳转登录页
        // this.$router.push({ name: 'xx', query: { .... }})  地址栏明文传输
        // this.$router.push({ name: 'xx, params: { .... }})  不会展示在地址栏的传参  (命名路由)
        this.$router.push({
          name: 'login',
          params: {
            username: this.username,
            password: this.password
          }
        })
      } else {
        this.$toast.fail(message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

.register {
  padding: 20px;
  .close {
    i {
      font-size: 27px;
    }
  }
  .logo {
    text-align: center;
    i {
      font-size: 126px;
      color: #d81e06;
    }
  }
  .register-btn {
    margin-top: 10px;
  }
  .go-login {
    font-size: 16px;
    text-align: center;
    padding-top: 20px;
    a {
      color: blue;
    }
  }
}
</style>
